package cn.itcast.sy7.filter;

import cn.itcast.sy7.entity.User;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;


@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if ("itcast".equals(username) && "123456".equals(password)) {
            HttpSession session = request.getSession();
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            session.setAttribute("user", user);

            String autoLogin = request.getParameter("autologin");
            if (autoLogin != null) {
                Cookie cookie = new Cookie("autologin", username + "-" + password); // 注意：密码不应明文存储，应加密
                cookie.setMaxAge(Integer.parseInt(autoLogin));
                cookie.setPath(request.getContextPath());
                response.addCookie(cookie);
            }

            response.sendRedirect(request.getContextPath() + "/index.jsp");
        } else {
            request.setAttribute("errMsg", "用户名或密码错误");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }
}